#include <gameuicontroller.h>
#include <gameuievent.h>
#include <macro.h>
#include <tui.h>
#include <cocos2d.h>
USING_NS_CC;

GameUIController* GameUIController::s_instance = NULL;
GameUIController* GameUIController::I()
{
	if( NULL == s_instance ){
		s_instance = new GameUIController();
		if (s_instance && s_instance->init()){   
			s_instance->autorelease();
		}else{   
			CC_SAFE_DELETE(s_instance);
			return NULL;
		}   
	}
	return s_instance;
}

GameUIController::GameUIController()
{
	/** register event callback, tui_event_cb_table defined in gameuievent.h,
	   	gameuievent.h is generated by flash cs TGameUITool extension.
	 */
	int ncb = sizeof(tui_event_cb_table)/sizeof(tui_event_cb_table[0]);
	TuiEventCallBackTable* ecb = NULL;
	for( int i=0; i<ncb; ++i ){
		ecb = tui_event_cb_table+i;
		registerEventCallBack( ecb->event, ecb->callback );
		tLogDebug( "register event: %s", ecb->event );
	}
}

GameUIController::~GameUIController()
{
}

void GameUIController::on_event_panel_start_click_btn_start( void*o, TEvent* e )
{
	//close all panels at first
	closeAll();
	
	//show a panel by gaven name
	Tui* ui_game = showTui( s_t_panel_game );

	//run action with a child control of the ui_game panel
	CCNode* btn_help = ui_game->getControl( s_t_btn_help );
	if( btn_help ){
		CCMoveBy* action = CCMoveBy::actionWithDuration(0.3, ccp( 0, 10 ));
		CCActionInterval* back = action->reverse();
		CCActionInterval* pSequence = (CCActionInterval*)CCSequence::actions(action, back, NULL);
		CCRepeatForever* actionloop = CCRepeatForever::actionWithAction(pSequence);
		btn_help->runAction( actionloop );
	}
}

void GameUIController::on_event_panel_start_click_btn_sound( void*o, TEvent* e )
{
	//o is the button who sender the event
	CCMenuItemImage* pbutton = (CCMenuItemImage*)o;
	pbutton->setEnabled(false);
}

void GameUIController::on_event_panel_game_click_btn_back( void*o, TEvent* e )
{
	//close all panels at first
	closeAll();
	showTui( s_t_panel_start );
}

void GameUIController::on_event_panel_game_click_btn_help( void*o, TEvent* e )
{
	//you may get a Tui by its name
	Tui* panel_game = getTui( s_t_panel_game );
	CCNode* game_rect = panel_game->getControl( s_t_panel_game_rect );

	//just remove all children simply here
	game_rect->removeAllChildrenWithCleanup(true);

	//you may add child to a control, it would be sprite, menu, Tui or ... what you like.
	CCSprite* psprite = CCSprite::create( CCFileUtils::sharedFileUtils()->fullPathFromRelativePath( "cogs.png" ) );
	game_rect->addChild(psprite);

	CCRotateBy* action = CCRotateBy::actionWithDuration( 3.0f, 360.0f );
	CCActionInterval* back = action->reverse();
	CCActionInterval* pSequence = (CCActionInterval*)CCSequence::actions(action, back, NULL);
	CCRepeatForever* actionloop = CCRepeatForever::actionWithAction(pSequence);
	psprite->runAction( actionloop );
}
